import 'package:flutter/material.dart';
import 'package:get/get.dart';
import '../controller/network_demo_controller.dart';
import '../../../core/state/universal_state_wrapper.dart';
import '../../../core/state/page_state.dart';

class NetworkDemoPage extends GetView<NetworkDemoController> {
  const NetworkDemoPage({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('网络请求演示'),
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        actions: [
          Obx(() => IconButton(
            onPressed: controller.isRefreshing ? null : controller.refreshUsers,
            icon: controller.isRefreshing
                ? const SizedBox(
                    width: 20,
                    height: 20,
                    child: CircularProgressIndicator(strokeWidth: 2),
                  )
                : const Icon(Icons.refresh),
            tooltip: '刷新',
          )),
          PopupMenuButton<String>(
            onSelected: (value) {
              switch (value) {
                case 'toggle_api':
                  controller.toggleApiMode();
                  break;
                case 'network_error':
                  controller.simulateNetworkError();
                  break;
                case 'permission_error':
                  controller.simulatePermissionError();
                  break;
              }
            },
            itemBuilder: (context) => [
              PopupMenuItem(
                value: 'toggle_api',
                child: Row(
                  children: [
                    const Icon(Icons.swap_horiz),
                    const SizedBox(width: 8),
                    Obx(() => Text(controller.useRealApi ? '切换到 Mock' : '切换到 API')),
                  ],
                ),
              ),
              const PopupMenuItem(
                value: 'network_error',
                child: Row(
                  children: [
                    Icon(Icons.wifi_off),
                    SizedBox(width: 8),
                    Text('模拟网络错误'),
                  ],
                ),
              ),
              const PopupMenuItem(
                value: 'permission_error',
                child: Row(
                  children: [
                    Icon(Icons.lock),
                    SizedBox(width: 8),
                    Text('模拟权限错误'),
                  ],
                ),
              ),
            ],
          ),
        ],
      ),
      body: Obx(() => UniversalStateWrapper(
        state: controller.pageState,
        errorMessage: controller.errorMessage,
        onRetry: controller.retryLoad,
        child: RefreshIndicator(
          onRefresh: controller.refreshUsers,
          child: ListView.builder(
            physics: const AlwaysScrollableScrollPhysics(),
            itemCount: controller.users.length,
            itemBuilder: (context, index) {
              final user = controller.users[index];
              return Card(
                margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 4),
                child: ExpansionTile(
                  leading: CircleAvatar(
                    backgroundColor: Theme.of(context).primaryColor,
                    child: Text(
                      user.name.isNotEmpty ? user.name[0] : '?',
                      style: const TextStyle(color: Colors.white),
                    ),
                  ),
                  title: Text(
                    user.name,
                    style: const TextStyle(fontWeight: FontWeight.bold),
                  ),
                  subtitle: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text('用户名: ${user.username}'),
                      Text('邮箱: ${user.email}'),
                    ],
                  ),
                  children: [
                    Padding(
                      padding: const EdgeInsets.all(16),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          _buildInfoSection('联系信息', [
                            '电话: ${user.phone}',
                            '网站: ${user.website}',
                          ]),
                          const SizedBox(height: 16),
                          _buildInfoSection('地址信息', [
                            '街道: ${user.address.street} ${user.address.suite}',
                            '城市: ${user.address.city}',
                            '邮编: ${user.address.zipcode}',
                            '坐标: ${user.address.geo.lat}, ${user.address.geo.lng}',
                          ]),
                          const SizedBox(height: 16),
                          _buildInfoSection('公司信息', [
                            '公司: ${user.company.name}',
                            '口号: ${user.company.catchPhrase}',
                            '业务: ${user.company.bs}',
                          ]),
                        ],
                      ),
                    ),
                  ],
                ),
              );
            },
          ),
        ),
      )),
      floatingActionButton: Obx(() => FloatingActionButton(
        onPressed: controller.pageState.hasError ? controller.retryLoad : controller.refreshUsers,
        tooltip: controller.pageState.hasError ? '重试' : '刷新',
        child: Icon(controller.pageState.hasError ? Icons.refresh : Icons.people),
      )),
    );
  }

  Widget _buildInfoSection(String title, List<String> items) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          title,
          style: const TextStyle(
            fontWeight: FontWeight.bold,
            fontSize: 16,
          ),
        ),
        const SizedBox(height: 8),
        ...items.map((item) => Padding(
          padding: const EdgeInsets.only(left: 16, bottom: 4),
          child: Text(item),
        )),
      ],
    );
  }
}